<template>
  <div 
    class="text-component"
    :style="textStyles"
    @dblclick="handleDoubleClick"
    v-if="!isEditing"
  >
    {{ component.content || '双击编辑文本' }}
  </div>
  
  <el-input
    v-if="isEditing"
    v-model="editContent"
    :style="inputStyles"
    @blur="handleBlur"
    @keyup.enter="handleBlur"
    ref="inputRef"
  />
</template>

<script>
import { defineProps, ref, onMounted } from 'vue';

export default {
  name: 'TextComponent',
  props: {
    component: {
      type: Object,
      required: true,
      description: '文本组件配置'
    },
    isPreview: {
      type: Boolean,
      default: false,
      description: '是否预览模式'
    }
  },
  setup(props) {
    const isEditing = ref(false);
    const editContent = ref('');
    const inputRef = ref(null);
    
    // 文本样式
    const textStyles = {
      width: '100%',
      height: '100%',
      display: 'flex',
      alignItems: 'center',
      justifyContent: props.component.textAlign || 'center',
      fontSize: props.component.fontSize ? `${props.component.fontSize}px` : '16px',
      color: props.component.color || '#333333',
      backgroundColor: props.component.backgroundColor || 'transparent',
      fontWeight: props.component.fontWeight || 'normal',
      fontStyle: props.component.fontStyle || 'normal',
      textDecoration: props.component.textDecoration || 'none',
      overflow: 'hidden',
      whiteSpace: props.component.whiteSpace || 'normal',
      textOverflow: props.component.textOverflow || 'ellipsis'
    };
    
    // 输入框样式
    const inputStyles = {
      ...textStyles,
      border: '1px solid #409eff',
      padding: '4px',
      boxSizing: 'border-box'
    };
    
    // 双击编辑文本
    const handleDoubleClick = () => {
      if (props.isPreview) return;
      
      isEditing.value = true;
      editContent.value = props.component.content || '';
      
      // 延迟聚焦，确保输入框已渲染
      onMounted(() => {
        inputRef.value?.focus();
      });
    };
    
    // 失去焦点时保存
    const handleBlur = () => {
      isEditing.value = false;
      if (editContent.value !== props.component.content) {
        props.component.content = editContent.value;
      }
    };
    
    return {
      isEditing,
      editContent,
      inputRef,
      textStyles,
      inputStyles,
      handleDoubleClick,
      handleBlur
    };
  }
};
</script>

<style scoped>
.text-component {
  cursor: text;
  user-select: text;
}
</style>
    